package server.controller.service.impl;

import common.model.entity.User;
import server.DataBuffer;
import server.controller.dao.UserDao;
import server.controller.dao.impl.UserDaoImpl;
import server.controller.service.UserService;

import java.util.List;

/**
 * 〈service〉
 */

public class UserServiceImpl implements UserService {
    int key = DataBuffer.x;
    /** 新增用户
     * @return*/
    @Override
    public User addUser(User user) {
        UserDao dao = new UserDaoImpl();
        user.setId((long) ++key);
        dao.insert(user);
        return user;
    }

    /** 用户登录 */
    @Override
    public User login(Long id, String password){
        User result = null;
        List<User> users = loadAllUser();
        for (User user : users) {
            if(id.equals(user.getId()) && password.equals(user.getPassword())){
                result = user;
                break;
            }
        }
        return result;
    }

    /** 根据ID加载用户 */
    @Override
    public User loadUser(Long id){
        User result = null;
        List<User> users = loadAllUser();
        for (User user : users) {
            if(id == user.getId()){
                result = user;
                break;
            }
        }
        return result;
    }

    /**
     * 加载最新key
     */
    @Override
    public long loadKey() {
        UserDao dao = new UserDaoImpl();
        return dao.queryKey();
    }

    /**
     * 更新key
     */
    @Override
    public void upKey() {
        UserDao dao = new UserDaoImpl();
        dao.updateKey();
    }


    /** 加载所有用户 */
    @Override
    public List<User> loadAllUser() {
        List<User> list = null;
        UserDao dao = new UserDaoImpl();
        try {
            list = dao.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void saveUser(User user) {
        try {
            UserDao dao = new UserDaoImpl();
            dao.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args){
        List<User> users = new UserServiceImpl().loadAllUser();
        for (User user : users) {
            System.out.println(user);
        }
    }
}
